<?php

namespace App\Http\Middleware;

use App\Http\Controllers\Api\Token;
use Closure;
use Illuminate\Http\Request;

class ApiTokenCheck
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        date_default_timezone_set("UTC");
        $token = $request->header()['token'][0];
        try{
            Token::getInstance()->validatorToken($token);
        }catch (\RuntimeException $exception){
            return  response()->json(['status'=>201,'msg'=>json_decode($exception->getMessage())->msg]);
        }
        $request['uid']=Token::getInstance()->getUserWithToken($token);
        return $next($request);
    }
}
